package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v6"
	"log"
	"time"
)

//传入参数
type listParam struct {
	page      int
	size      int
	ip        string
	startTime int64
	endTime   int64
	level     string
	hostname  string
}

func main() {
	//连接es
	client, err := elastic.NewClient(elastic.SetURL("http://192.168.3.47:9200"))
	if err != nil {
		panic(err)
	}
	now := time.Now()
	//分组排序
	//LO_SHIPMODE.keyword  LO_SHIPMODE 是text类型，加上.keyword进行标识匹配
	shopAggregation := elastic.NewTermsAggregation().Field("LO_SHIPMODE.keyword").OrderByCountDesc()
	orderAggregation := elastic.NewTermsAggregation().Field("LO_ORDERPRIORITY.keyword").OrderByCountDesc()
	shopAggregation = shopAggregation.SubAggregation("orderAggregation", orderAggregation)

	searchResult, err := client.Search().
		Index("flight").
		Query(elastic.NewMatchAllQuery()).
		Aggregation("shopAggregation", shopAggregation).
		Size(5).
		Pretty(true).Do(context.Background())
	if err != nil {
		// Handle error
		panic(err)
	}
	t := time.Now()
	log.Println(t.Sub(now))

	agg, found := searchResult.Aggregations.Terms("shopAggregation")
	if !found {
		// 没有查询到terms聚合结果
		log.Fatalf("we should have a terms aggregation called %q", "timeline")
	}
	// 遍历桶数据
	for _, userBucket := range agg.Buckets {
		// 每一个桶都有一个key值，其实就是分组的值，可以理解为SQL的group by值
		user := userBucket.Key

		// 查询嵌套聚合查询的数据
		// 因为我们使用的是Date histogram聚合，所以需要使用DateHistogram函数和聚合名字获取结果
		histogram, found := userBucket.DateHistogram("orderAggregation")
		if found {
			// 如果找到Date histogram聚合结果，则遍历桶数据
			for _, year := range histogram.Buckets {
				var key string
				if s := year.KeyAsString; s != nil {
					// 因为返回的是指针类型，这里做一下取值运算
					key = *s
				}
				// 打印结果
				fmt.Printf("user %q has %d tweets in %q\n", user, year.DocCount, key)
			}
		}
	}
}
